﻿using Microsoft.EntityFrameworkCore;
using mozhi.smarterp.Finance.Basedatas.Repository;
using mozhi.smarterp.Finance.EntityFrameworkCore;
using mozhi.smarterp.Finance.Querys;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using System.Linq;

namespace mozhi.smarterp.Finance.Basedatas
{
    public class DimensionGroupValueRepository : EfCoreRepository<FinanceDbContext, DimensionGroupValue , Guid>, IDimensionGroupValueRepository
    {
        public DimensionGroupValueRepository(IDbContextProvider<FinanceDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<List<DimensionGroupValue>> FindAsync(DimensionGroupValuePageQuery query)
        {
            List<Guid> ids = null;

            if(query.ItemValues!=null)
            {
                ids = DbContext.Set<DimensionGroupValueItem>().AsNoTracking().Where(x=> query.ItemValues.Contains(x.Value)).Select(x=>x.DimensionGroupValueId).ToList();

                ids = ids.Distinct().ToList();

                query.Ids = query.Ids ?? new List<Guid>();

                query.Ids.AddRange(ids);

                query.Ids = query.Ids.Distinct().ToList();
            }    
                

            var dbQuery = DbContext.Set<DimensionGroupValue>().Include(x => x.Items).AsNoTracking();

            var result = await dbQuery
                .WhereIf(query.Ids != null && query.Ids.Count > 0, x => query.Ids.Contains(x.Id))
                .WhereIf(query.Id.HasValue, x => x.Id == query.Id)
                .WhereIf(!query.UniqueValue.IsNullOrEmpty(), x => x.UniqueValue == query.UniqueValue)
                .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
                .ToListAsync();

            return result;
        }

        public async Task<List<DimensionGroupValue>> GetAsync(DimensionGroupValuePageQuery query)
        {
            var dbQuery = DbContext.Set<DimensionGroupValue>().Include(x => x.Items);

            var result = await dbQuery
                .WhereIf(query.Id.HasValue, x => x.Id == query.Id)
                .WhereIf(!query.UniqueValue.IsNullOrEmpty(), x => x.UniqueValue == query.UniqueValue)
                .Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize)
                .ToListAsync();

            return result;
        }

        public async Task<List<DimensionGroupValue>> UpdateAsync(List<DimensionGroupValue> values)
        {
            foreach (var item in values)
            {
                await UpdateAsync(item);
            }

            return values;
        }
    }
}
